package com.ywqf_api.common;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.View;

import com.ywqf_api.common.constants.Constants;
import com.ywqf_api.util.PropertiesUtil;

/**
 * 
 * @author ran
 *
 */
public class SpringExceptionResolver implements HandlerExceptionResolver{

    private Logger logger= LoggerFactory.getLogger(this.getClass());
    
    @Autowired
    private View jsonView;
    
    private String isDebug;
    
    private final String errorView = "error/error";

    public ModelAndView resolveException(HttpServletRequest request,
                                         HttpServletResponse response,
                                         Object handler, Exception ex) {

        String url = request.getRequestURL().toString();
        logger.error("Catch Exception, url:" + url, ex);
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        ResponseBody body = handlerMethod.getMethodAnnotation(ResponseBody.class);
        if (isDebug.equals(Constants.ISDEBUG)) {
            // 调试模式下，打印详细异常错误信息
            JsonData ret = JsonData.fail(ex.getMessage());
            if (body==null) {
            	return new ModelAndView(errorView,ret.toMap());
			}else {
				return new ModelAndView(jsonView,ret.toMap());
			}
        } else {
            // 生产模式下，返回统一异常处理页面
            JsonData ret = JsonData.fail(PropertiesUtil.getProperty("error_msg"));
            return new ModelAndView("error/error",ret.toMap());
        }
    }

	public void setIsDebug(String isDebug) {
		this.isDebug = isDebug;
	}
    
}
